import React from 'react';
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx';
import { Synergy } from '../../document/components/Portal/Portal';

import {
  Row, Col, Tabs, Button, Input, Modal, Icon,
  Spin, Popover, message, DatePicker,
} from 'antd';
import isEmpty from 'lodash/isEmpty';

import { WeaShare, WeaVideo } from 'ecCom';

const confirm = Modal.confirm;
const RangePicker = DatePicker.RangePicker;

import {
  WeaReqTop,
  WeaRightMenu,
  WeaErrorPage,
  WeaTools,
  WeaNewScroll,
  WeaRichText,
  WeaInputSearch,
  WeaCheckbox,
  WeaAuth,
  WeaFormItem,
  WeaDialog,
  WeaUpload,
  WeaLocaleProvider,
} from 'ecCom';

import { WeaTableNew } from 'comsMobx';

const WeaTable = WeaTableNew.WeaTable;
import ReplyItem from './Detail/ReplyItem';

import DocLog from './DocLog';

import '../style/detail.less';
import '../style/htmlContent.less';
import * as Util from '../util/transf';
import BackToE8 from './Detail/BackToE8';
import { trans } from '../util/callWithParams';
import { GetUrlParam, openAppLink } from '../util/Util.js';

import CustomButtonEdit from './Detail/CustomButtonEdit';
import CustomButton from './Detail/CustomButton';
import Star from './Detail/Star';
import DataListItem from './Detail/DataListItem';
import AccColumns from './Detail/AccColumns';

const getLabel = WeaLocaleProvider.getLabel;


@inject('documentDetailStore')
@observer
class Detail extends React.Component {
  constructor(props) {
    super(props);
    this.isIE = !!window.ActiveXObject || 'ActiveXObject' in window;
    const idReg = window.location.search.match(/(\?|\&)id=\d+/g);
    const blnOspReg = window.location.search.match(/(\?|\&)blnOsp=\d+/g);
    const viewReply = window.location.search.match(/(\?|\&)viewReply=\d+/g);
    const confirmMsg = window.__warmMessage ? window.__warmMessage : '';
    const userAgent = navigator.userAgent;
    if (confirmMsg !== '') {
      confirm({
        content: confirmMsg,
        onOk: () => {
        },
      });
    }
    // 获取是否是正文，获取文件名称
    let requestDocReg = window.location.search.match(/(\?|\&)requestDoc=\d+/g);
    requestDocReg = requestDocReg && requestDocReg.length === 1 ? requestDocReg[0].split('=')[1] : '';
    let documentTitleField = '';
    if (requestDocReg === '1' && window.location.href.indexOf('documentTitleField=') > 0) {
      let documentTitleFieldHref = window.location.href.substring(window.location.href.indexOf('documentTitleField=') + 19);
      if (documentTitleFieldHref.indexOf('&') > 0) documentTitleFieldHref = documentTitleFieldHref.substring(0, documentTitleFieldHref.indexOf('&'));
      documentTitleField = documentTitleFieldHref;
      if (documentTitleField === '-3') documentTitleField = '-1';
    }

    this.state = {
      docid: idReg && idReg.length === 1 ? idReg[0].split('=')[1] : '',
      blnOsp: blnOspReg && blnOspReg.length === 1 ? blnOspReg[0].split('=')[1] : '',
      viewReply: viewReply && viewReply.length === 1 ? viewReply[0].split('=')[1] : '',
      richVisible: false,
      richValue: '',
      status: '',
      score: -1,
      toTopVisible: false,

      requestDoc: requestDocReg,
      requestDocSubject: requestDocReg === '1' ? window.parent.WfForm.getFieldValue(`field${documentTitleField}`) : '',

      fileVersionVisible: false,
      shareEditVisible: false,
      shareAddVisible: false,
      markDetailVisible: false,
      collectVisible: false,
      list: [],
      upStatus: '',
      isAutoExtendInfo: window.__isAutoExtendInfo || '0',

      richTextUploadStatus: false,
      uploadFiles: [],
      uploadImgs: [],
      workFlows: [],
      docs: [],
      isIE: (this.isIE && userAgent.indexOf('MSIE 9') >= 0), // 判断是否是ie9
    };

    this.onTabsChange = this.onTabsChange.bind(this);
    this.onPraiseClick = this.onPraiseClick.bind(this);
    this.onToolsChange = this.onToolsChange.bind(this);
    this.doSubmit = this.doSubmit.bind(this);
    this.onOperatesClick = this.onOperatesClick.bind(this);
    this.doShareAddDelete = this.doShareAddDelete.bind(this);
    this.getBottomBarConfig = this.getBottomBarConfig.bind(this);
    this.extentsConfig = [
      '-',
      {
        name: 'Browser', // 浏览按钮组件，浏览按钮类型及其他属性按照浏览按钮说明
        show: <i className="icon-coms-Journal reply-extend-icon" style={{ cursor: 'pointer' }} title={getLabel(22243, '文档')} />,
        type: '37', // 浏览按钮类型
        title: getLabel(22243, '文档'), // 浏览按钮标题
      },
      {
        name: 'Browser', // 浏览按钮组件，浏览按钮类型及其他属性按照浏览按钮说明
        show: <i className="icon-coms-Workflow-o reply-extend-icon" style={{ cursor: 'pointer' }} title={getLabel(30045, '流程')} />,
        type: '152', // 浏览按钮类型
        title: getLabel(30045, '流程'), // 浏览按钮标题
      },
    ];
    this.collectParams = {
      favname: `${getLabel(22243, '文档')}：${window.__docsubject}`,
      favouritetype: 1,
      objid: this.state.docid,
      importantlevel: 1,
      link: `/spa/document/index.jsp?id=${this.state.docid}${window.__moudleParams}&router=1#/main/document/detail`,
      onOpen: this.collectOpen,
    };
    if (confirmMsg !== '' && window.__showByHtml === '0') {
    	this.onTabsChange('param');
    }
    let agent = window.navigator.userAgent.toLowerCase();
    // if(agent.indexOf("android")!==-1 || agent.indexOf("iphone")!==-1){
    //   let url = `/spa/document/static4mobile/index.html#/doc/${this.state.docid}`;
    //   if(window.em && (typeof window.em.checkJsApi === 'function') && window.em.checkJsApi('openLink')){
    //     window.em.openLink({
    //       url:url,
    //       openType:1
    //     });
    //   }else{
    //     var _win = window;
    //     _win.location = url;
    //   }
    // }
    this.moreBtn = {
      datas: [
        {
          key: '1',
          disabled: false,
          icon: '',
          content: getLabel(86, '保存'),
          onClick: this.onSave,
        },
      ],
      collectParams: {
        favname: '',
        favouritetype: 2,
        objid: 0,
        importantlevel: 1,
      },
    };
  }

  componentDidMount() {
    // 一些初始化请求
    const { documentDetailStore } = this.props;
    const { docid, blnOsp, isAutoExtendInfo, viewReply } = this.state;
    // 要排除的moudleimgid
    documentDetailStore.excludeImgId = window.__moudlePicIds;
    if (documentDetailStore.excludeImgId) {
      documentDetailStore.moudleIds = documentDetailStore.excludeImgId.split(',');
    }
    documentDetailStore.getBasic({ docid });
    documentDetailStore.searchAcc({ docid });
    if (blnOsp === '1') {
      this.setState({ shareEditVisible: true });
      documentDetailStore.searchShare({ id: docid });
      documentDetailStore.canShareAddEdit({ id: docid });
    }
    if (window.__convertFile) {
      documentDetailStore.convertFile(trans(window.__convertFile));
    }
    if (isAutoExtendInfo == '1') {
      documentDetailStore.doDocAutoExtendInfo({ id: docid }, window.__moudleParams);
    }
    if (viewReply == '1') {
      documentDetailStore.setTabKey('reply');
      documentDetailStore.getReplyList({ docid });
    }
    WeaVideo.renderVideoPlayer();

    window.openDocumentAppLink = (obj, linkid, linkType) => {
      openAppLink(obj, linkid, linkType);
    };
  }

  componentDidUpdate() {
    const { documentDetailStore } = this.props;
    let fileid = '';
    let flag = true;
    // 图片预览
    $('#wea-doc-detail-content-main-scroll img').unbind('click');
    $('#wea-doc-detail-content-main-scroll img').bind('click', (event) => {
        if ($(event.srcElement).parent().is('a')) {
          return;
       }
     const imgPool = [];
     let indexNum = 0;
     // clickImgUrl当前点击的图片的来源链接，clickImgId当前点击图片的id
     let clickImgUrl = event.srcElement.src;
     let clickImgId = GetUrlParam(clickImgUrl, 'fileid');
     $('#wea-doc-detail-content-main-scroll img').each(function () {
       imgPool.push($(this).attr('src'));
     });
     let moudleids = toJS(documentDetailStore.moudleIds);
     let imgShow = imgPool.filter((val) => {
        fileid = GetUrlParam(val, 'fileid');
        flag = true;
        moudleids.forEach((moudleid) => {
          // 如果当前的图片id属于模板图片,或者没有fileid（即非下载链接图片）不展示
          if (toJS(moudleid) === fileid) {
            flag = false;
          }
        });
        if (fileid === '') {
          flag = false;
        }
        return flag;
     });
     for (let i = 0; i < imgShow.length; i++) {
        let imgid = GetUrlParam(imgShow[i], 'fileid');
       if (clickImgId === imgid) {
         break;
       } else {
         indexNum++;
       }
     }
     // 判断是否展示图片组件
     let isShowPicture = true;
     moudleids.forEach((moudleid) => {
       // 如果当前点击的图片id属于模板图片,或者没有fileid（即非下载链接图片）不展示
        if (moudleid === clickImgId) {
          isShowPicture = false;
        }
     });
     if (clickImgId === '') {
        isShowPicture = false;
     }

     if (isShowPicture) {
       window.IMCarousel.showImgScanner4Pool(true, imgShow, indexNum, null, window.top);
     }
   });
 }
 onSave = (key) => {
  const { docid } = this.state;
  const { documentDetailStore: { topSet, setTop } } = this.props;
  this.setState({ toTopVisible: false });
  setTop({ docid, ...toJS(topSet) });
 }
 onListChange = (ids, list) => {
    this.setState({
      uploadFiles: list,
    });
  }
  getBottomBarConfig() {
    const { docid } = this.state;
    let bottomBarConfig = [];
    let datas = this.state.uploadFiles || [];
    datas = datas.map(data => ({
        fileExtendName: data.docextendname,
        fileid: data.id,
        filelink: data.url,
        filename: data.name,
        filesize: data.downName,
        // imgSrc	string	是	附件图标
        loadlink: data.downUrl,
        // showLoad	bool	否	是否可下载
        // showDelete	bool	否	是否可删除
        // isImg	bool	否	非图片模式下是表示文件是否是图片格式
        ...data,
      }));
    bottomBarConfig.push({
      name: 'Upload', // 上传组件
      type: 'list', // 上传组件类型
      show: (
        <div className="wea-doc-detail-upload">
          <div className="rich-button">
            <i className="icon-coms-currency-Enclosure" title={getLabel(128095, ' 上传附件')} />
            {datas.length > 0 && <div className="red-point" />}
            <span className="button-text">{getLabel(517827, ' 附件')}</span>
          </div>
        </div>
      ), // 使用 antd 图标
      uploadUrl: `/api/doc/upload/uploadFile?model=reply&docid=${docid}`, // 上传地址
      category: '/api/doc/upload/uploadFile?model=reply', // 文档目录
      onListChange: this.onListChange,
      datas,
    });
    return bottomBarConfig;
  }
  linkNewestDoc = () => {
    window.location.href = window.__linkNewestDoc;
  }
  // 新版本提示
  getNewVersionNotice() {
    return (
      <div className="wea-doc-detail-notice"
        style={
        { display: window.__hasNewestWarm === '1' ? 'block' : 'none' }}
      >
        <a onClick={this.linkNewestDoc}>{getLabel(386309, '当前版本不是最新，点击查看最新版本')}</a>
      </div>
    );
  }

  // tab
  getTabPane() {
    const { documentDetailStore } = this.props;
    const { tabInfo, replyCount } = documentDetailStore;
    return toJS(tabInfo).map((data) => {
      let tab = data.value;
      if (data.key === 'reply') {
        tab = <span>{data.value}({replyCount})</span>;
      }
      if (data.key === 'acc') {
        tab = <span>{data.value}({documentDetailStore.accTableStore.count})</span>;
      }
      return <Tabs.TabPane ecId={`${this && this.props && this.props.ecId || ''}_undefined@veeoog@${data.key}`} tab={tab} key={data.key} />;
    });
  }

  onTabsChange(key) {
    const { documentDetailStore } = this.props;
    const { attrDatas, scoreDatas, comStore } = documentDetailStore;
    const { docid } = this.state;
    documentDetailStore.setTabKey(key);
    key === 'acc' && documentDetailStore.searchAcc({ docid });
    // key === 'log' && comStore.doSearch('DocLog', {docid});
    if (key === 'share') {
      documentDetailStore.searchShare({ id: docid });
      documentDetailStore.canShareAddEdit({ id: docid });
    }
    key === 'version' && documentDetailStore.searchVersionTable({ docid });
    key === 'param' && attrDatas.length === 0 && documentDetailStore.getAttr({ docid });
    key === 'score' && scoreDatas.length === 0 && documentDetailStore.getScore({ docid });
    key === 'reply' ? documentDetailStore.getReplyList({ docid }) : this.setState({ richValue: '', richVisible: false });
  }

  // bottom
  getBottom() {
    const { documentDetailStore } = this.props;
    const { basicInfo, readCount } = documentDetailStore;
    if (!basicInfo.doclastmoddatetime || readCount === '') return null;
    // const text = getLabel(386308, '最后由{user}编辑于{time}阅读{count}');
    return (
      <span className="wea-doc-detail-content-text-sub">
        <span>{getLabel(126385, '最后由')}</span>
        <span>{`${basicInfo.doclastmoduser}`}</span>
        <span>{`${getLabel(126386, '编辑于')}${basicInfo.doclastmoddatetime}`}</span>
        <span>{`${getLabel(260, '阅读')} (${readCount})`}</span>
      </span>
    );
  }

  // 附件操作
  onCancelFileVersion = () => this.setState({ fileVersionVisible: false })
  onOperatesClickFileVersion = (record, index, operate, flag) => {
    flag === '0' && open(`/weaver/weaver.file.FileDownload?fileid=${record.imagefileid}`
      + `&download=1${window.__moudleParams}`);
  }
  getFileVersion() {
    const { documentDetailStore } = this.props;
    const { fileVersionVisible } = this.state;
    return (
      <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@z35tip`}
        icon="icon-coms-doc"
        iconBgcolor="#f14a2d"
        title={getLabel(19587, '版本信息')}
        style={{ width: 800 }}
        maskClosable={false}
        visible={fileVersionVisible}
        onCancel={this.onCancelFileVersion}
        buttons={[
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@dbkto5@$versionDialogCancel`}
            type="ghost"
            onClick={this.onCancelFileVersion}
          >{getLabel(309, '关闭')}</Button>,
        ]}
      >
        <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@4gytap`} scrollId="wea_doc_detail_content_file_version" height="100%">
          <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@jwdmw2`}
            comsWeaTableStore={documentDetailStore.fileVersionTableStore}
            onOperatesClick={this.onOperatesClickFileVersion}
          />
        </WeaNewScroll>
      </WeaDialog>
    );
  }

  // 打分详情
  onCancelMarkDetail = () => this.setState({ markDetailVisible: false })
  getMarkDetail() {
    const { documentDetailStore } = this.props;
    const { markDetailVisible } = this.state;
    return (
      <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@a3dpzt`}
        title={getLabel(386310, '打分详细')}
        icon="icon-coms-doc"
        iconBgcolor="#f14a2d"
        style={{ width: 800 }}
        maskClosable={false}
        visible={markDetailVisible}
        onCancel={this.onCancelMarkDetail}
        buttons={[
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@kinc2k@givePointDialogCancel`}
            type="ghost"
            onClick={this.onCancelMarkDetail}
          >{getLabel(309, '关闭')}</Button>,
        ]}
      >
        <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@qjrozf`} scrollId="wea_doc_detail_content_file_version" height="100%">
          <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@o22wh1`}
            comsWeaTableStore={documentDetailStore.markDetailTableStore}
          />
        </WeaNewScroll>
      </WeaDialog>
    );
  }

  onOperatesClick = (record, index, operate, flag) => {
    const { documentDetailStore } = this.props;
      const { docid } = this.state;
    const { imagefileid, versionid, id } = record;
    flag == '0' && window.openFullWindowForXtable(`/spa/document/index2file.jsp?id=${id}&imagefileId=${imagefileid}&versionId=${versionid}&isEdit=1&router=1`
      + `&${window.__moudleParams}#/main/document/fileView`);// 编辑
    flag == '1' && open(`/weaver/weaver.file.FileDownload?fileid=${imagefileid}`
      + `&download=1${window.__moudleParams}`);
    if (flag == '2') {
      let _params = { docid, imagefileid, versionid };
      if (window.__moudleParams) {
        let moudleParams = window.__moudleParams.split('&');
        for (let i = 0; i < moudleParams.length; i++) {
          if (moudleParams[i] != '' && moudleParams[i].indexOf('=') > -1) {
            _params[moudleParams[i].split('=')[0]] = moudleParams[i].split('=')[1];
          }
        }
      }

      documentDetailStore.searchFileVersion(_params);
      this.setState({ fileVersionVisible: true });
    }
  }

  // 右键菜单
  onChangeList = (ids, l) => this.setState({ list: l })
  onUploadingList = (s) => {
    const { documentDetailStore } = this.props;
    const { list, docid } = this.state;
    this.setState({ upStatus: s });
    s === 'uploaded' && list.length === 1 && documentDetailStore.docAccReplace({
      id: docid,
      newfileid: list[0].fileid,
    });
  }
  getButtons() {
    const { documentDetailStore, ecId } = this.props;
    let rightMenus = toJS(documentDetailStore.rightMenus);
    const { list, upStatus, docid } = this.state;
    const btnArr = [];
    rightMenus = rightMenus.filter(menu => menu.isTop === '1');
    rightMenus.forEach((btn) => {
      if (btn.type === 'BTN_ACC_REPLACE') {
        btnArr.push(<WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@h22cwj@${btn.type}`}
          style={{ paddingTop: 0 }}
          title={getLabel(517712, '替换附件')}
          uploadUrl="/api/doc/upload/uploadFile"
          category="string"
          multiSelection={false}
          maxFilesNumber={1}
          maxUploadSize={btn.customData.maxUploadSize}
          mixUploadSize={btn.customData.mixUploadSize}
          limitType={btn.customData.limitType}
          onChange={this.onChangeList}
          onUploading={this.onUploadingList}
        >
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@q7fg1m@${btn.type}_button`} type="primary" loading={upStatus === 'uploading'}>{btn.menuName}</Button>
        </WeaUpload>);
      } else if (btn.type === 'BTN_ACC_EDIT') {
        btnArr.push(<CustomButtonEdit btn={btn} ecId={`${this && this.props && this.props.ecId || ''}_Button@0ffvwv@${btn.type}`} />);
      } else {
        btnArr.push(<CustomButtonEdit btn={btn} ecId={`${this && this.props && this.props.ecId || ''}_Button@uolti6@${btn.type}`} onRightMenuClick={this.onRightMenuClick} />);
      }
    });
    return btnArr;
  }

  getRightMenu() {
    const { documentDetailStore } = this.props;
    let rightMenus = toJS(documentDetailStore.rightMenus);
    const { list, docid, isIE } = this.state;
    const btnArr = [];
    rightMenus.forEach((btn) => {
      if (documentDetailStore.tabKey == 'content') {
        if (btn.type == 'BTN_DOWNLOAD') {
          return;
        }
      }

      let com = {
        key: btn.type,
        icon: <i className={btn.menuIcon} />,
        content: btn.menuName,
        onClick: this.onRightMenuClick,
        title: btn.menuName,
      };
      if (btn.type === 'BTN_ACC_REPLACE') {
        com.content = (
          <div className="replace-file">
            <WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@uiaz0k@${btn.type}`}
              style={{ paddingTop: 0 }}
              title={btn.menuName}
              uploadUrl="/api/doc/upload/uploadFile"
              category="string"
              multiSelection={false}
              maxFilesNumber={1}
              maxUploadSize={btn.customData.maxUploadSize}
              mixUploadSize={btn.customData.mixUploadSize}
              limitType={btn.customData.limitType}
              onChange={this.onChangeList}
              onUploading={this.onUploadingList}
            >
              <div style={{ paddingLeft: isIE ? 42 : '' }}>{btn.menuName}</div>
            </WeaUpload></div>);
      }
      btnArr.push(com);
    });
    return btnArr;
  }

  onRightMenuClick = (key) => {
    const { documentDetailStore } = this.props;

    let rightMenus = toJS(documentDetailStore.rightMenus),
basicInfo = toJS(documentDetailStore.basicInfo);
    const { docid } = this.state;
    const selectedUser = window.__currentUser || '';

    key === 'BTN_SUBMIT' && documentDetailStore.draftSubmit({ id: docid }, (data) => {
      data.status === 1 && data.link ? window.location.href = data.link : message.error(data.msg);
    });

    key === 'BTN_SHARE_DOC' && (documentDetailStore.shareVisible = true);

    if (key === 'BTN_SHARE') {
      this.setState({ shareEditVisible: true });
      documentDetailStore.searchShare({ id: docid });
      documentDetailStore.canShareAddEdit({ id: docid });
    }
    if (key === 'BTN_SAVE') {
      document.getElementById('ofdshow').contentWindow.saveFile();
    }

    if (key === 'BTN_REPLY' || key === 'BTN_LOG') {
      this.onTabsChange(key.split('_')[1].toLocaleLowerCase());
      this.setState({ richVisible: true });
    }

    key === 'BTN_DOWNLOAD' &&
    rightMenus.forEach((btn) => {
      if (btn.type === key) {
        // open(`/weaver/weaver.file.FileDownload?${btn.params}${window.__moudleParams}`);


		    if (window.__docisLock) {
				try {
					document.getElementById('webOffice').contentWindow.WebSaveLocal();
					// iframe1.contentWindow.WebSaveLocal();
				} catch (e) {
					open(`/weaver/weaver.file.FileDownload?${btn.params}${window.__moudleParams}`);
				}
             //   }else if(!window.__is2015Open && (!!window.ActiveXObject || "ActiveXObject" in window )){
			} else {
				open(`/weaver/weaver.file.FileDownload?${btn.params}${window.__moudleParams}`);
            }
      }
    });
    key === 'BTN_CREATE_WORKFLOW' &&
    rightMenus.forEach((btn) => {
      if (btn.type === key) {
        open(btn.params
          ? `/spa/workflow/index_form.jsp#/main/workflow/req?docid=${docid}&iscreate=1&${btn.params}`
          : `/spa/workflow/static/index.html#/main/workflow/add?docid=${docid}`);
      }
    });
    if (key === 'BTN_EDIT') {
      documentDetailStore.setAttachHideContent(true);
      documentDetailStore.docfileisCheckOut({ docid, resource: 'detail' });
    }
    key === 'BTN_RELATE_WORKFLOW' && open(`/spa/workflow/static/index.html#/main/workflow/queryFlowResult?docids=${docid}&needTree=false&docidsspan=${basicInfo.docSubject}`);
    key === 'BTN_CREATE_PLAN' && open(`/spa/workplan/static/index.html#/main/wp/workPlanCreateSingle?selectedUser=${selectedUser}&type=create&docid=${docid}`);
    key === 'BTN_PRINT' && this.print();
    key === 'BTN_STORE' && open(
      `/systeminfo/BrowserMain.jsp?url=/favourite/FavouriteBrowser.jsp&fav_pagename=
      ${escape(`${getLabel(22243, '文档')}:${basicInfo.docSubject}`)}
      &fav_uri=/docs/docs/DocDsp.jsp&fav_querystring=
      ${escape(`id=${docid}`)}&mouldID=doc`);
    key === 'BTN_HELP' && open('/formmode/apps/ktree/ktreeHelp.jsp?pathKey=docs/docs/DocDsp.jsp');
    key === 'BTN_DELETE' && documentDetailStore.deleteWarm({ docid });
    key === 'BTN_IN_VALIDATE' && documentDetailStore.invalidate({ docid });
    if (key === 'BTN_TO_TOP') {
      documentDetailStore.getTopSet({ docid });
      this.setState({ toTopVisible: true });
    }
    if (key == 'BTN_CANCLE_TOP') {
       documentDetailStore.setTop({ docid, isTop: 0 });
    }
    if (key == 'BTN_PUBLISH') {
      documentDetailStore.publishDoc({ docid });
    }
    key === 'BTN_RE_OPEN' && documentDetailStore.reOpen({ id: docid });
    key === 'BTN_RE_LOAD' && documentDetailStore.reLoad({ id: docid });
    if (key === 'BTN_ACC_EDIT') {
      const btn = rightMenus.find(v => v.type === key);
      btn && window.openFullWindowForXtable(`/spa/document/index2file.jsp?${btn.params}${window.__moudleParams}#/main/document/fileView`);
    }
  }

  print = () => {
    if ($('.wea-doc-detail-content-main iframe').length > 0) {
    	window.docPrint();
    } else {
      const preContent = $('.wea-doc-detail-content-main').html() || window.__preContent || '';
      let printWindow = window.open('打印窗口', '_blank');
      printWindow.document.write(preContent);
      printWindow.document.close();
      printWindow.print();
      printWindow.close();
    }
  }

  onCancelTopModal = () => this.setState({ toTopVisible: false })
  updateTopSetOfCheckbox = (v) => {
    const { documentDetailStore } = this.props;
    documentDetailStore.updateTopSet({ isTop: v });
  }
  updateTopSetOfRangePicker = (v, dateString) => {
    const { documentDetailStore } = this.props;
    documentDetailStore.updateTopSet({ fromDate: dateString[0], toDate: dateString[1] });
  }
  // 文档置顶
  getToTopModal() {
    const { documentDetailStore } = this.props;
    const topSet = toJS(documentDetailStore.topSet);
    const { toTopVisible, docid } = this.state;
    return (
      <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@fxarnt`}
        title={getLabel(23784, '文档置顶')}
        style={{ width: 800 }}
        icon={'icon-coms-doc'}
        iconBgcolor={'#F14A2D'}
        maskClosable={false}
        visible={toTopVisible}
        onCancel={this.onCancelTopModal}
        buttons={
          [
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@i1xp7o@docSetTopDialogSaveBtn`}
              type="primary"
              onClick={this.onSave}
            >{getLabel(86, '保存')}</Button>,
          ]
        }
        moreBtn={this.moreBtn}
      >
        <div style={{ padding: '30px 0px 30px 150px' }}>
          <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@oxm957`}
            label={getLabel(23784, '文档置顶')}
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 18 }}
          >
            <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@rg60jh`}
              value={topSet.isTop || '0'}
              onChange={this.updateTopSetOfCheckbox}
            />
          </WeaFormItem>
          <div style={{ 'margin-top': '8px' }} />
          <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@1qw94p`}
            label={getLabel(15030, '有效期')}
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 18 }}
          >
            <RangePicker ecId={`${this && this.props && this.props.ecId || ''}_RangePicker@3rfns2`}
              value={[topSet.fromDate || '', topSet.toDate || '']}
              onChange={this.updateTopSetOfRangePicker}
            />
          </WeaFormItem>
        </div>
      </WeaDialog>
    );
  }

  // 弹框共享信息
  onCancelShareEditModal = () => {
    const { documentDetailStore } = this.props;
    const { shareTableStore } = documentDetailStore;
    this.setState({ shareEditVisible: false });
    shareTableStore.setSelectedRowKeys([]);
  }
  onConfirmShareEdit = () => {
    const { docid } = this.state;
    const { documentDetailStore } = this.props;
    documentDetailStore.afterShareSave({ id: docid });
    documentDetailStore.setHideContent(false);
  }
  onCancelShareEdit = () => {
    const { documentDetailStore } = this.props;
    documentDetailStore.setHideContent(false);
  }
  onSubmitShareEditModal = () => {
    this.onCancelShareEditModal();
    const { documentDetailStore } = this.props;
    documentDetailStore.setHideContent(true);
    confirm({
      content: getLabel(387336, '确认要提交文档吗？'),
      onOk: this.onConfirmShareEdit,
      onCancel: this.onCancelShareEdit,
    });
  }
  doShareAdd = () => {
    const { documentDetailStore } = this.props;
    const { docid } = this.state;
    this.setState({ shareAddVisible: true });
    documentDetailStore.getAddShare({ docid });
  }
  getShareEditModal() {
    const { documentDetailStore } = this.props;
    const { shareAddEditBtn, shareTableStore, basicInfo: { docstatus } } = documentDetailStore;
    const selectedRowKeys = toJS(shareTableStore.selectedRowKeys);
    const { shareEditVisible, docid } = this.state;
    const hasAddBtn = shareAddEditBtn.hasAddBtn === '1';
    const hasDelBtn = shareAddEditBtn.hasDelBtn === '1';
    return (
      <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@gqba3n`}
        title={getLabel(1985, '文档共享')}
        className="wea-doc-detail-share-dialog"
        icon="icon-coms-doc"
        iconBgcolor="#f14a2d"
        style={{ width: 780, height: 524 }}
        maskClosable={false}
        visible={shareEditVisible}
        onCancel={this.onCancelShareEditModal}
        buttons={
          docstatus == 0 ? [
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@r3pz6q@doc-detail-share-dialog-save-btn`}
              type="primary"
              onClick={this.onSubmitShareEditModal}
            >{getLabel(725, '提交')}</Button>,
          ] : []
        }
      >
        <div className="wea-table-edit">
          <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@7ucmqr`} className="wea-table-edit-title">
            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@n1u16b`}>
              <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@pvd8jo`}
                style={{ width: 22 }}
                type="primary"
                title={getLabel(91, '删除')}
                size="small"
                disabled={!hasDelBtn || !`${selectedRowKeys}`}
                onClick={this.doShareAddDelete}
              ><span className="icon-coms-form-delete-hot" /></Button>
              <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@esyytm`}
                style={{ width: 22 }}
                type="primary"
                title={getLabel(1421, '新增')}
                size="small"
                disabled={!hasAddBtn}
                onClick={this.doShareAdd}
              ><span className="icon-coms-Add-to-hot" /></Button>
            </Col>
          </Row>
          <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@f3jg84`}>
            <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@pho13l`}
              className="wea-doc-detail-share-table-list"
              comsWeaTableStore={shareTableStore}
            />
          </WeaNewScroll>
        </div>
      </WeaDialog>
    );
  }

  // 添加共享
  doShareAddSubmit = (v) => {
    const { documentDetailStore } = this.props;
    const { docid } = this.state;
    documentDetailStore.doShareAddSubmit({ ...v, id: docid });
    this.setState({ shareAddVisible: false });
  }
  doShareAddCancel=() => {
    this.setState({ shareAddVisible: false });
  }
  getShareAddModal() {
    const { documentDetailStore } = this.props;
    const { shareAddVisible, docid } = this.state;
    let { conditions } = documentDetailStore;
    conditions = toJS(conditions);
    if (conditions.length === 0) {
      return null;
    }
    return (
      <WeaAuth ecId={`${this && this.props && this.props.ecId || ''}_WeaAuth@7e22l5`}
        title={getLabel(18645, '添加共享')}
        visible={shareAddVisible}
        conditions={conditions}
        onOk={this.doShareAddSubmit}
        onCancel={this.doShareAddCancel}
      />
    );
  }
  deleteShare = () => {
    const { documentDetailStore } = this.props;
    const { shareTableStore } = documentDetailStore;
    const selectedRowKeys = toJS(shareTableStore.selectedRowKeys);
    const { docid } = this.state;
    documentDetailStore.deleteShare({ docid, shareId: `${selectedRowKeys.join()}` });
  }
  doShareAddDelete() {
    confirm({
      content: getLabel(15097, '确定要删除吗？'),
      onOk: this.deleteShare,
    });
  }

  // tab 内容的 title
  onSearchAcc = (v) => {
    const { documentDetailStore } = this.props;
    const { docid } = this.state;
    documentDetailStore.searchAcc({
      docid, imageFileName: v,
    });
  }
  downloadMul = () => {
    const { documentDetailStore } = this.props;
    const { isdownload, accTableStore } = documentDetailStore;
    const selectedRowKeys = toJS(accTableStore.selectedRowKeys);
    let candownload = false;
    if (isdownload == '0' && selectedRowKeys.length != 0) {
       candownload = false;
    } else {
      candownload = true;
    }
    !candownload && open(
      '/weaver/weaver.file.FileDownload?onlydownloadfj=1&download=1&labelid=32407'
      + `&fieldids=${selectedRowKeys},${window.__moudleParams}`,
    );
  }
  getTitle() {
    const { documentDetailStore } = this.props;
    const { tabKey, shareTableStore, accTableStore, shareAddEditBtn, docAutoExtendInfo, isdownload } = documentDetailStore;
    const { bacthDownload } = docAutoExtendInfo;
    const selectedRowKeys = toJS(accTableStore.selectedRowKeys);
    const { docid } = this.state;
    let contentLeft = null;
    let contentRight = null;
    const hasAddBtn = shareAddEditBtn.hasAddBtn === '1';
    const hasDelBtn = shareAddEditBtn.hasDelBtn === '1';
    if (tabKey === 'acc') {
      contentLeft = getLabel(21704, '附件列表');
      let disabled = null;
      if (bacthDownload) {
       contentRight = (
        <span style={{ marginRight: 20 }}>
          <WeaInputSearch ecId={`${this && this.props && this.props.ecId || ''}_WeaInputSearch@aw5hyh`}
            style={{ width: 180, height: 30, verticalAlign: 'middle' }}
            placeholder={getLabel(386311, '请输入附件名称')}
            onSearch={this.onSearchAcc}
          />
        </span>
      );
      } else {
        if (!bacthDownload && (selectedRowKeys.length === 0)) {
          disabled = true;
        } else {
          disabled = false;
        }
        let candownload = false;
        if (isdownload == '0' && selectedRowKeys.length != 0) {
           candownload = false;
        } else {
          candownload = true;
        }
        contentRight = (
          <span style={{ marginRight: 20 }}>
            <WeaInputSearch ecId={`${this && this.props && this.props.ecId || ''}_WeaInputSearch@9eocoo`}
              style={{ width: 180, verticalAlign: 'middle' }}
              placeholder={getLabel(386311, '请输入附件名称')}
              onSearch={this.onSearchAcc}
            />
             <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@0tqugo`}
               style={{ marginLeft: 10 }}
               type="primary"
               disabled={candownload}
               onClick={this.downloadMul}
             >
			        {getLabel(32407, '批量下载')}
            </Button>
          </span>

        );
      }
    }
    if (tabKey === 'version') {
      contentLeft = getLabel(19587, '版本信息');
      contentRight = null;
    }
    if (tabKey === 'ref') {
      contentLeft = getLabel(32991, '相关资源信息');
      contentRight = <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@il8pao`}>{getLabel(32121, '文档订阅')}</Button>;
    }
    if (tabKey === 'children') {
      contentLeft = getLabel(131470, '子文档列表');
      contentRight = null;
    }
    if (tabKey === 'share') {
      contentLeft = getLabel(1279, '共享信息');
      contentRight = (
        <span className="wea-table-edit" style={{ display: 'block', height: 0 }}>
          <span className="wea-table-edit-title"
            style={{ display: 'inline-block', paddingTop: 16, border: 0 }}
          >
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@av2sa6`}
              style={{ width: 22 }}
              type="primary"
              title={getLabel(91, '删除')}
              size="small"
              disabled={!hasDelBtn || toJS(shareTableStore.selectedRowKeys).length === 0}
              onClick={this.doShareAddDelete}
            ><span className="icon-coms-form-delete-hot" /></Button>
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@mdcnki`}
              style={{ width: 22 }}
              type="primary"
              title={getLabel(1421, '新增')}
              size="small"
              disabled={!hasAddBtn}
              onClick={this.doShareAdd}
            ><span className="icon-coms-Add-to-hot" /></Button>
          </span>
        </span>
      );
    }
    return (
      <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@p94wa4`} className="wea-doc-detail-content-inner-title">
        <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@qhqyr5`} span={12} style={{ paddingLeft: 20 }}>
          {contentLeft}
        </Col>
        <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@eqdaha`} span={12} style={{ textAlign: 'right' }}>
          {contentRight}
        </Col>
      </Row>
    );
  }

  // 文档属性
  getAttr() {
    const { documentDetailStore } = this.props;
    const { attrDatas } = documentDetailStore;
    const items = [];
    attrDatas.forEach((item) => {
      const col = item.column || 1;
      items.push(
        <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@yoir5k@${item.label}-Col`} span={12 * col}>
          <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@kmgafq@${item.label}`}
            label={item.label}
            labelCol={{ span: 6 / col }}
            wrapperCol={{ span: 24 - 10 / col }}
            underline
          >
            <div
              className="wea-field-readonly"
              dangerouslySetInnerHTML={{ __html: item.value }}
            />
          </WeaFormItem>
        </Col>,
      );
    });
    return (
      <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@yzgqhb`} className="wea-doc-detail-content-inner-attr">
        {items}
      </Row>
    );
  }

  // 文档打分
  onStarClick = (params = {}) => {
    this.setState({ score: -1 });
    const { documentDetailStore } = this.props;
    const { starIndex: index, starScore: _score, starRemark: remark } = params;
    documentDetailStore.updateMarkInfo({ mark: index + 1 === _score ? 0 : index + 1, remark });
  }
  onMouseEnter = index => this.setState({ score: index + 1 })
  onMouseLeave = () => this.setState({ score: -1 })
  updateMarkInfo = (e) => {
    const { documentDetailStore } = this.props;
    documentDetailStore.updateMarkInfo({ remark: e.target.value });
  }
  onRankClick = () => {
    const { documentDetailStore } = this.props;
    const { scoreDatas, markInfo, comStore } = documentDetailStore;
    const { remark } = markInfo;
    const { docid, score } = this.state;
    const _score = Number(markInfo.mark || 0);
    const scoreShow = score > -1 ? score : _score;
    if (scoreShow || remark) {
      documentDetailStore.doMark({ docid, score: scoreShow, remark });
    } else {
      message.warning(`${getLabel(386312, '请输入评论内容')}！`);
    }
  }
  showDocDetail = () => {
    const { documentDetailStore } = this.props;
    const { docid } = this.state;
    documentDetailStore.searchMarkDetail({ docid });
    this.setState({ markDetailVisible: true });
  }
  getRank() {
    const { documentDetailStore } = this.props;
    const { scoreDatas, markInfo, comStore } = documentDetailStore;
    const { remark } = markInfo;
    const { docid, score } = this.state;
    const _score = Number(markInfo.mark || 0);
    const scoreShow = score > -1 ? score : _score;
    const stars = [0, 0, 0, 0, 0];
    const hasPH = !remark;
    const props = hasPH ? { placeholder: `${getLabel(386312, '请输入评论内容')} ~` } : { value: remark };
    return (
      <div className="wea-doc-detail-content-inner-tab-content-rank">
        <p style={{ fontSize: 14 }}>{getLabel(386313, '我的评分')}</p>
        <div className="wea-doc-detail-content-inner-tab-content-rank-star">
          <span>{getLabel(386314, '评价文档')}</span>
          {
            stars.map((s, index) => (
                <Star
                  key={index}
                  starIndex={index}
                  starScore={_score}
                  starRemark={remark}
                  className={`icon-coms-Collection${index < scoreShow ? '2' : ''}`}
                  onClick={this.onStarClick}
                  onMouseEnter={this.onMouseEnter}
                  onMouseLeave={this.onMouseLeave}
                />
              ))
          }
        </div>
        <Input ecId={`${this && this.props && this.props.ecId || ''}_Input@wbxh1r`}
          type="textarea"
          {...props}
          autosize={{ minRows: 6, maxRows: 6 }}
          onChange={this.updateMarkInfo}
        />
        <div style={{ textAlign: 'right', padding: '15px 0' }}>
          <CustomButton
            ecId={`${this && this.props && this.props.ecId || ''}_Button@0z7pai`}
            type="ghost"
            size="large"
            style={{ width: 93, borderRadius: 3 }}
            onClick={this.onRankClick}
          >
            {getLabel(725, '提交')}
          </CustomButton>
        </div>
        <div className="wea-doc-detail-content-inner-tab-content-rank-list">
          <div>{getLabel(30296, '总评')}</div>
          {
            scoreDatas.map((item, i) => (
                <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@4q1jk4@${item.label}`}
                  label={item.label}
                  labelCol={{ span: 8 }}
                  wrapperCol={{ span: 16 }}
                >
                  <span style={{ color: i === 2 ? '#000' : '#ffa741', fontSize: 14 }}>
                    {item.value}
                  </span>
                </WeaFormItem>
              ))
          }
        </div>
        <div style={{ 'text-align': 'right', 'padding-top': '10px' }}>
          <span className="wea-doc-detail-score-detail" onClick={this.showDocDetail}>{getLabel(18997, '详细情况')}</span>
        </div>
      </div>
    );
  }

  // 回复
  focusReply = () => {
    this.setState({ richVisible: true });
    this.refs.reply_main.focus();
  }
  onChangeRich=v => this.setState({ richValue: v })
  onStatusChange = s => this.setState({ status: s })
  onSubmitRichText = () => {
    const { docid } = this.state;
    let DocReplyContent = '';
    if (this.refs && this.refs.reply_main && this.refs.reply_main.getData) {
        DocReplyContent = this.refs.reply_main.getData();
    }
    if (DocReplyContent) {
      const { UploadImage, UploadFile, Browser152, Browser37 } = this.state;
      const { uploadFiles, workFlows, docs, uploadImgs, richValue } = this.state;
      const fieldAnnexupload = [],
fieldAnnexuploadName = [],
signdocids = [],
signdocnames = [],
         signworkflowids = [],
signworkflownames = [],
imgFileids = [],
imgFilenames = [];
      uploadFiles.forEach((v) => {
        fieldAnnexupload.push(v.fileid);
        fieldAnnexuploadName.push(v.filename);
      });
      docs.forEach((v) => {
        if (richValue.indexOf(v.id) > -1) { // 回复内容中存在时，才提交
        signdocids.push(v.id);
        signdocnames.push(v.name);
        }
      });
      workFlows.forEach((v) => {
        if (richValue.indexOf(v.id) > -1) { // 回复内容中存在时，才提交
          signworkflowids.push(v.id);
          signworkflownames.push(v.name);
        }
      });
      uploadImgs.forEach((v) => {
        imgFileids.push(v.fileid);
        imgFilenames.push(v.filename);
      });

      this.doSubmit(
        {
          docid,
          content: DocReplyContent,
          replyid: '',
          'field-annexupload': fieldAnnexupload.join(','),
          'field-annexupload-name': fieldAnnexuploadName.join('////~~weaversplit~~////'),
          signdocids: signdocids.join(','),
          signdocnames: signdocnames.join('////~~weaversplit~~////'),
          signworkflowids: signworkflowids.join(','),
          signworkflownames: signworkflownames.join('////~~weaversplit~~////'),
          imgFileids: imgFileids.join(','),
          imgFilenames: imgFilenames.join('////~~weaversplit~~////'),
        },
        0, UploadImage, UploadFile, Browser152, Browser37);
      this.setState({
        richValue: '',
        richVisible: false,
        uploadFiles: [],
        uploadImgs: [],
        workFlows: [],
        docs: [],
      });
    if (this.refs && this.refs.reply_main && this.refs.reply_main.getData) {
        this.refs.reply_main.setData('');
    }
    } else {
      message.warning(getLabel(126383, '回复内容不能为空！'));
    }
  }
  onCancelRichText = () => this.setState({
    richValue: '',
    richVisible: false,
    uploadFiles: [],
    uploadImgs: [],
    workFlows: [],
    docs: [],
  })
  getReply() {
    const { docid, richVisible, richValue, status, richTextUploadStatus } = this.state;
    return (
      <div className="wea-doc-detail-reply">
        {this.getReplyList()}
        <div className="wea-doc-detail-reply-rich" style={{ padding: richVisible ? 0 : 10 }}>
          <div style={{ display: richVisible ? 'none' : 'block' }} onClick={this.focusReply}>
            <i className="icon-coms-edit" /> {getLabel(126377, '写回复')}
          </div>
          <div style={{ display: richVisible ? 'block' : 'none' }}>
            <WeaRichText ecId={`${this && this.props && this.props.ecId || ''}_WeaRichText@hzg69g`}
              ref="reply_main"
              // value={richValue}
              ckConfig={{
                toolbar: [
                  { name: 'document', items: ['Source'] },
                  {
                    name: 'paragraph',
items: ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-',
                      'NumberedList', 'BulletedList'],
                  },
                  { name: 'styles', items: ['Format'] },
                  { name: 'styles', items: ['Font'] },
                  { name: 'styles', items: ['FontSize'] },
                  { name: 'colors', items: ['TextColor'] },
                  { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike'] },
                  { name: 'links', items: ['Link', 'Unlink'] },
                  { name: 'insert', items: ['Image', 'Table', 'Smiley'] },
                  { name: 'tools', items: ['Maximize'] },
                  { name: 'clipboard', items: ['Undo', 'Redo'] },
                ],
                height: 100,
                uploadUrl: `/api/doc/upload/uploadFile?model=reply&docid=${docid}`,
              }}
              extentsConfig={this.extentsConfig}
              onChange={this.onChangeRich}
              onStatusChange={this.onStatusChange}
              onToolsChange={this.onToolsChange}
              bottomBarConfig={this.getBottomBarConfig()}
            />
            {
              status === 'ready' &&
              <div className="wea-doc-detail-reply-rich-btm">
                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@bepok8`}
                  type="primary"
                  onClick={this.onSubmitRichText}
                  disabled={richTextUploadStatus}
                  loading={richTextUploadStatus}
                >{getLabel(725, '提交')}</Button>
                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@3brvir`}
                  style={{ marginLeft: 8 }}
                  type="ghost"
                  onClick={this.onCancelRichText}
                >{getLabel(31129, '取消')}</Button>
              </div>
            }
          </div>
        </div>
      </div>
    );
  }

  onToolsChange(name = '', ids = '', list = [], type = '') {
    const stateList = this.state[`${name}_${type}`];
    const newList = list.map((item) => {
      const _item = { ...item };
      if (name === 'Upload' && type === 'image') {
        _item.string = `=${_item.fileid}`;
        this.setState({ uploadImgs: list });
      } else if (name === 'Upload' && type === 'file') {
        this.setState({ uploadFiles: list });
      } else if (name === 'Browser') {
        type == '37' ? this.setState({ docs: this.state.docs.concat(list) }) : this.setState({ workFlows: this.state.workFlows.concat(list) });
        _item.string = `,${item.id},`;
      }
      return _item;
    });
    this.setState({ [`${name}_${type}`]: (stateList ? stateList.concat(newList) : newList) });
    return Util.transfStr(name, ids, list, type);
  }

  // 回复列表
  onRichSubmit = (params, hasMore, UploadImage, UploadFile, Browser152, Browser37) => {
    const { docid } = this.state;
    this.doSubmit({ docid, ...params },
      hasMore, UploadImage, UploadFile, Browser152, Browser37);
  }
  getMoreReplyMain = (params) => {
    const { documentDetailStore } = this.props;
    const { docid } = this.state;
    documentDetailStore.getMoreReplyMain({ docid, ...params });
  }
  getMoreReplyChild = (params) => {
    const { documentDetailStore } = this.props;
    const { docid } = this.state;
    documentDetailStore.getMoreReplyChild({ docid, ...params });
  }
  deleteReply = (params) => {
    const { documentDetailStore } = this.props;
    const { docid } = this.state;
    documentDetailStore.deleteReply({ docid, ...params });
  }
  getReplyList() {
    const { documentDetailStore } = this.props;
    const { replyList, replyLoading } = documentDetailStore;
    const { docid, richVisible } = this.state;
    if (toJS(replyList).length === 0 && !replyLoading) {
      return (
        <div className="wea-doc-detail-reply-list"
          style={{ textAlign: 'center', marginTop: 150, color: '#999' }}
        >
          <p><i className="icon-document-No-response" style={{ fontSize: 50 }} /></p>
          <p style={{ fontSize: 20, marginTop: 20 }}>{getLabel(83553, '暂无数据')}</p>
        </div>
      );
    }
    const _replyList = this.resetReplyList(toJS(replyList));
    return (
      <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@gbhjmv`} spinning={replyLoading}>
        <div className="wea-doc-detail-reply-list"
          style={richVisible ? { marginBottom: 208 } : {}}
        >
          {
            _replyList.map((item, i) => {
              let isLast = _replyList.length === i + 1;
              if (!documentDetailStore.replyHaveMore) {
                item.ishave = false;
              }
              return (
                <ReplyItem ecId={`${this && this.props && this.props.ecId || ''}_ReplyItem@rxb7km@${i}`}
                  data={item}
                  docid={docid}
                  isLast={isLast}
                  extentsConfig={this.extentsConfig}
                  onToolsChange={this.onToolsChange}
                  onPraiseClick={this.onPraiseClick}
                  onRichSubmit={this.onRichSubmit}
                  getMoreReplyMain={this.getMoreReplyMain}
                  getMoreReplyChild={this.getMoreReplyChild}
                  deleteReply={this.deleteReply}
                />
              );
            })
          }
        </div>
      </Spin>
    );
  }

  // 回复列表重组
  resetReplyList(replyList) {
    let _replyList = replyList.filter(item => item.replyid === item.replymainid);
    _replyList = _replyList.map((_item) => {
      let __item = { ..._item, children: [] };
      replyList.map((item) => {
        if (item.replymainid === _item.replyid
          && item.replyid !== item.replymainid) {
          __item = { ...__item, children: [...__item.children, item] };
        }
        return item;
      });
      return __item;
    });
    return _replyList;
  }

  // 回复列表点赞
  onPraiseClick(data, isPraise) {
    const { documentDetailStore } = this.props;
    documentDetailStore.setPraise({
      type: 1,
docid: data.docid,
      praiseid: data.replyid,
    }, isPraise);
  }

  doSubmit(params, hasMore, UploadImage, UploadFile, Browser152, Browser37) {
    const { documentDetailStore } = this.props;
    const { docid } = this.state;
    const { content } = params;
    const _params = { ...params };
    if (UploadImage) {
      const { ids, names } = this.extentsfilter(content, UploadImage);
      _params.imgFileids = ids;
      _params.imgFilenames = names;
    }
    if (UploadFile) {
      const { ids, names } = this.extentsfilter(content, UploadFile);
      _params['field-annexupload'] = ids;
      _params['field-annexupload-name'] = names;
    }
    if (Browser152) {
      const { ids, names } = this.extentsfilter(content, Browser152);
      _params.signworkflowids = ids;
      _params.signworkflownames = names;
    }
    if (Browser37) {
      const { ids, names } = this.extentsfilter(content, Browser37);
      _params.signdocids = ids;
      _params.signdocnames = names;
    }
    documentDetailStore.saveReply(_params, hasMore);
    documentDetailStore.getBasic({ docid });
  }

  extentsfilter(content, list) {
    const ids = [];
    const names = [];
    const _list = list.filter(item => content.indexOf(item.string) >= 0);
    _list.forEach((item) => {
      ids.push(item.fileid || item.id);
      names.push(item.filename || item.name);
    });
    return { ids: ids.join(','), names: names.join('////~~weaversplit~~////') };
  }
  backToE8 = () => {
    const { docid } = this.state;
    window.location.href = `/docs/docs/DocDsp.jsp?id=${docid}${window.__moudleParams}`;
  }
  getE8Button() {
    return (
      <BackToE8 ecId={`${this && this.props && this.props.ecId || ''}_BackToE8@7ag35b`} onClick={this.backToE8} />
    );
  }
  onClickAutoExtendInfo = () => this.setState({ isAutoExtendInfo: '0' })
  doDocAutoExtendIcon = () => {
    const { docid } = this.state;
    const { documentDetailStore } = this.props;
    this.setState({ isAutoExtendInfo: '1' });
    documentDetailStore.doDocAutoExtendInfo({ id: docid }, window.__moudleParams);
  }
  getAutoExtendInfo = () => {
    const { documentDetailStore } = this.props;
    let { docAutoExtendInfo } = documentDetailStore;
    const { isAutoExtendInfo, docid } = this.state;
    docAutoExtendInfo = toJS(docAutoExtendInfo);
    let { dataList = [], hasMore = false, canDownload = false } = docAutoExtendInfo;
    let com = null;
    if (!isEmpty(dataList)) {
      com = isAutoExtendInfo == '1' ?
        (<div className="auto-extend-info-con">
          <div className="con-title">
            <i className="icon-coms-currency-Enclosure" />
            <span>{getLabel(517827, '附件')}</span>
            <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@hfsl9y`} type="cross" onClick={this.onClickAutoExtendInfo} />
          </div>
          <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@d3bmqc`} className="con-content">
            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@k6r96k`} span={23}>
              <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@lat2je`}>
                {
                  dataList.map((v, index) => {
                    let href = `/spa/document/index2file.jsp?id=${v.id}&imagefileId=${v.imagefileid}&versionId=${v.versionId}&router=1${v.otherparams && v.otherparams}${window.__moudleParams}#/main/document/fileView`;
                    return (
                      <DataListItem v={v} index={index} ecId={this && this.props && this.props.ecId || ''} onOperatesClick={this.onOperatesClick} />
                    );
                  })
                }
              </Row>
            </Col>
            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@qzjl1s`} span={1}>
              {
                hasMore && <span className="hasMore" onClick={() => this.onTabsChange('acc')}>MORE<Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@ey46tm`}
                  type="double-right"
                /></span>
              }
            </Col>
          </Row>
        </div>) :
        (<div className="auto-extend-info-icon" onClick={this.doDocAutoExtendIcon}>
          <i className="icon-coms-currency-Enclosure" />
        </div>);
    }
    return com;
  }
  getColumns = (columns) => {
    const { documentDetailStore } = this.props;
    const { tabKey, mainImagefile } = documentDetailStore;
    if (tabKey != 'acc') {
      return columns;
    }
    const { docid } = this.state;
    return columns.map((item) => {
      if (item.dataIndex == 'imagefilename') {
        return {
          ...item,
          render: (text, record, index) => {
            const { versionspan, imagefileid, randomFieldId, versionid, otherParamsspan } = record;
            let otherparams = otherParamsspan ? (`&${otherParamsspan}`) : '';
            let href = `/spa/document/index2file.jsp?id=${docid}&imagefileId=${imagefileid}&versionId=${versionid}&router=1${otherparams}${window.__moudleParams}#/main/document/fileView`;
            return (<AccColumns text={text} record={record} index={index} href={href} onOperatesClick={this.onOperatesClick} />);
          },
        };
      } else if (item.dataIndex == 'mainimagefile') {
        return {
          ...item,
          render: (text, record, index) => {
            const { versionspan, imagefileid, randomFieldId, versionid, otherParamsspan, mainimagefile } = record;
            return (
              <span>
                {imagefileid == mainImagefile
                  ? <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@dey71c`} type="check" />
                  : ''
                }
              </span>
            );
          },
        };
      }
      return item;
    });
  }
  collectOpen = (v1, v2) => {
    if (v1 !== v2 && v2) {
      this.setState({ collectVisible: true });
    }
    if (v1 !== v2 && v1) {
      this.setState({ collectVisible: false });
    }
  }
  setPraise = () => {
    const { documentDetailStore: { setPraise, praiseInfo } } = this.props;
    const { docid } = this.state;
    const isPraised = praiseInfo.isPraised === '1';
    setPraise({ docid, praiseid: docid, type: 0 }, !isPraised);
  }
  onVisibleChange = (bool) => {
    const { documentDetailStore } = this.props;
    documentDetailStore.shareVisible = bool;
  }
  render() {
    const { documentDetailStore } = this.props;
    const {
       loading, basicInfo, tabKey, praiseInfo,
      tabInfo, showSearchAd, replyLoading, hideContent = false,
      accTableStore, shareTableStore, versionTableStore, shareVisible, attachHideContent,
    } = documentDetailStore;
    const { docid, fileVersionVisible, markDetailVisible, shareEditVisible, shareAddVisible, requestDoc, collectVisible, viewReply } = this.state;
    const notShowOffice = fileVersionVisible || shareEditVisible || shareAddVisible || markDetailVisible || collectVisible;
    // 设置页标题
    if (basicInfo.docSubject && document.title != basicInfo.docSubject) {
      document.title = basicInfo.docSubject;
    }
    const title = basicInfo.docSubject || '';
    const isPraised = praiseInfo.isPraised === '1';
    const users = praiseInfo.users || [];
    const usersShow = praiseInfo.username && isPraised ? [...users, praiseInfo] : users;
    const preTitle = $('.wea-new-top-req-title-text').html() || window.__preTitle || '';
    const onlyUrl4Content = window.__onlyUrl4Content;
    const preContent = onlyUrl4Content ? window.__preContent : $('.wea-doc-detail-content-main').html() || window.__preContent || '';
    const markStyle = showSearchAd ? { height: '100%', overflow: 'hidden' } : null;
    const selectedUser = window.__currentUser || '';
    const bgColor = window.bgColor || '';
    let rightMenuDisabled = false;
    if (tabKey == 'content' && requestDoc == '1') {
      rightMenuDisabled = true;
    }
    return (
      <div className={`wea-doc-detail ${requestDoc === '1' ? 'wea-odoc-add' : ''}`}>
        {this.getNewVersionNotice()}
        <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@mclv6p`} datas={this.getRightMenu()} collectParams={this.collectParams} disabled={rightMenuDisabled}>
          <WeaReqTop ecId={`${this && this.props && this.props.ecId || ''}_WeaReqTop@ise7su`}
            title={
              title ?
                <span style={{ paddingLeft: 8, display: 'inline-block', width: '100%' }}>
                  <span style={{ display: 'inline-block' }} title={title}>{title}</span>
                  {
                  	praiseInfo && praiseInfo.canParse &&
	                  <span
  style={{
	                      fontSize: 16,
marginLeft: 13,
position: 'relative',
	                      color: isPraised ? '#ff9f01' : '#b2b2b2',
	                    }}
	                  >
	                    <i
  title={isPraised ? getLabel(32944, '取消赞') : getLabel(32942, '赞')}
  className="icon-coms-Good"
  style={{ cursor: 'pointer', marginRight: 2 }}
  onClick={this.setPraise}
	                    />
	                    <Popover ecId={`${this && this.props && this.props.ecId || ''}_Popover@ljaq0j`}
  overlayClassName="wea-doc-detail-top-reply-count-wrap"
  placement="bottomLeft"
  content={
	                               usersShow.length > 0 ?
	                                 <span>
	                            {
	                              usersShow.map((user, index) => (
	                                  <span style={{ marginRight: 5 }}>
	                                    <span
  dangerouslySetInnerHTML={{
	                                        __html: `<a href='javaScript:openhrm(${user.userid});'
	                                        onclick='pointerXY(event);'
	                                        style='color: #fff'>${user.username}</a>`,
	                                      }}
	                                    />
	                                    {usersShow.size - 1 > index ? ' , ' : ''}
	                                  </span>
	                                ))
	                            }
	                          </span>
	                                 : `${getLabel(386315, '还没有人点赞哦')}~`
	                             }
  trigger="hover"
	                    >
	                      <span className="wea-doc-detail-top-reply-count"
  style={{
	                        cursor: 'pointer',
verticalAlign: 'text-bottom',
	                        fontSize: 12,
color: isPraised ? '#ff9f01' : '#333',
	                      }}
	                      >
	                        ({users.length + (isPraised ? 1 : 0)})
	                    </span>
	                    </Popover>
	                  </span>
	               }
                </span>
                : <span dangerouslySetInnerHTML={{ __html: preTitle }} />
            }
            loading={accTableStore.loading || shareTableStore.loading || versionTableStore.loading || replyLoading || loading}
            icon={<i className="icon-coms-doc" />}
            iconBgcolor="#df583a"
            replaceTab={
              tabInfo.length === 0 ?
                <span style={{ display: 'block', height: 37 }} />
                :
                <Tabs ecId={`${this && this.props && this.props.ecId || ''}_Tabs@f4jg8l`}
                  activeKey={tabKey}
                  onChange={this.onTabsChange}
                >
                  {this.getTabPane()}
                </Tabs>
            }
            buttons={this.getButtons()}
            showDropIcon
            dropMenuDatas={this.getRightMenu()}
            dropMenuProps={{ collectParams: this.collectParams }}
            // onDropMenuClick={this.onRightMenuClick.bind(this)}
          >
            <div className="wea-doc-detail-content"
              style={window.__showByHtml === '0' && tabKey === 'content'
                   ? { padding: '0 0 39px 0' } : {}
                 }
            >
              <div className="wea-doc-detail-content-inner" style={{ overflow: 'hidden' }}>
                <div style={
                   tabKey === 'content' && !notShowOffice && !attachHideContent && !hideContent && !shareVisible
                  ? {
                    height: '100%',
                  }
                  :
                  {
                    height: '1px',
                    marginTop: '-1px',
                  }
              }
                >
                  <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@v4h4jc`} scrollId="wea-doc-detail-content-main-scroll" height="100%" direction="h" style={{ 'background-color': bgColor }}>
                    {/* <link href="/cloudstore/resource/pc/ckeditor-4.6.2/weaver/contents.css" type="text/css" rel="stylesheet"/> */}
                    {!onlyUrl4Content ? <div className="wea-doc-detail-content-main cke_editable"
                      style={hideContent && (!!window.ActiveXObject || 'ActiveXObject' in window) ? { height: '1px' } : {}}
                      dangerouslySetInnerHTML={{ __html: preContent }}
                    /> :
                    <div className="wea-doc-detail-content-main cke_editable"
                      style={hideContent && (!!window.ActiveXObject || 'ActiveXObject' in window) ? { height: '1px' } : {}}
                    >
                        <iframe id="webOffice" src={preContent} style={{ display: 'block', width: '100%', height: '100%', border: 0 }} />
                    </div>}
                  </WeaNewScroll>
                </div>
                <div className="wea-doc-detail-content-inner-tab-content"
                  style={{ display: tabKey === 'content' ? 'none' : 'block' }}
                >
                  <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@jyd7z1`} scrollId="wea_doc_detail_content" height="100%">
                    {
                      (tabKey === 'acc' || tabKey === 'version'
                        || tabKey === 'ref' || tabKey === 'children'
                        || tabKey === 'share') && this.getTitle()
                    }
                    <div style={{ display: tabKey === 'acc' ? 'block' : 'none' }}>
                      <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@d96wgl`}
                        comsWeaTableStore={accTableStore}
                        getColumns={this.getColumns}
                        onOperatesClick={this.onOperatesClick}
                      />
                    </div>
                    {
                      tabKey === 'param' && this.getAttr()
                    }
                    <div style={{ display: tabKey === 'share' ? 'block' : 'none' }}>
                      <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@fxpf0y`}
                        comsWeaTableStore={shareTableStore}
                      />
                    </div>
                    <div style={{ display: tabKey === 'version' ? 'block' : 'none' }}>
                      <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@yn9oc9`}
                        comsWeaTableStore={versionTableStore}
                      />
                    </div>
                    <div style={{ display: tabKey === 'log' ? 'block' : 'none', ...markStyle }}>
                      {tabKey === 'log'
                      && <DocLog ecId={`${this && this.props && this.props.ecId || ''}_DocLog@j9h5he`} docid={this.state.docid} searchType={['advanced']} needScroll={false} />}
                    </div>
                    {
                      tabKey === 'score' && this.getRank()
                    }
                    {
                      tabKey === 'reply' && this.getReply()
                    }
                  </WeaNewScroll>
                </div>
                {tabKey == 'content' && this.getAutoExtendInfo()}
              </div>
              {tabKey === 'content' && this.getBottom()}
              {this.getToTopModal()}
              {this.getFileVersion()}
              {this.getShareEditModal()}
              {this.getShareAddModal()}
              {this.getMarkDetail()}
              <WeaShare ecId={`${this && this.props && this.props.ecId || ''}_WeaShare@9g8bzq`}
                visible={shareVisible}
                onVisibleChange={this.onVisibleChange}
                shareParams={{
                  url: '/api/doc/mobile/systemDoc/addShare',
                  resourceid: docid,
                }}
                msginfo={[
                  {
                    content: basicInfo.docSubject, // 分享标题（必填）
                    desc: '', // 分享描述（非必填）
                    sysid: window.localStorage.emobile_ec_id, // EM中添加的集成系统的ID (必填: 按照demo给的传)
                    linkurl: `/common/chatResource/view.jsp?resourcetype=37&resourceid=${docid}&isfromchatshare=1&sharer=${selectedUser}`, // 消息链接地址（必填）
                    canforward: 1, // 消息是否允许转发 1：是（默认） 0：否
                    callbackurl: `/api/common/chatResource/addshare?resourcetype=37&resourceid=${docid}&isfromchatshare=1&firstSharer=${selectedUser}`, // 消息转发回调地址（非必填）
                    opentype: 1, // 移动端打开方式 1:app内打开（默认） 2：手机默认浏览器打开
                    opentype_pc: 2, // PC端打开方式 1:应用内打开（默认） 2：PC默认浏览器打开
                    sharetype: 'doc', // 分享数据类型："doc","workflow","task","pdoc","folder" ,"crm" 分别代表文档，流程，任务，云盘文档，云盘文件，客户名片
                    shareid: docid, // 分享的数据ID（必填）
                  },
                ]}
              />
            </div>
          </WeaReqTop>
        </WeaRightMenu>
        <Synergy ecId={`${this && this.props && this.props.ecId || ''}_Synergy@nbhrj6`} pathname="/document/detail" secid="-1" docid={docid} />
      </div>
    );
  }
}


Detail = WeaTools.tryCatch(React,
  props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@jstoks`} msg={props.error || getLabel(385218, '对不起，该页面异常，请联系管理员！')} />,
  { error: '' })(Detail);

export default Detail;
